package cn.js.websocket.controller;

import cn.js.websocket.vo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;
import java.security.Principal;

/**


 */
@RestController
public class WebSocketController {


    /**
     * 通过SimpMessagingTemplate模板向浏览器发送消息。如果是广播模式，可以直接使用注解@SendTo
     */
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;


    @SubscribeMapping("/topic/subscribeTest/{id}")
    public void subscribeTest(@DestinationVariable("id") String id, Principal principal) throws Exception {
        //Thread.sleep(1000); // simulated delay
        System.out.println("有人订阅了:"+principal.getName()+id);

        //return Arrays.asList("111","222","333");  在线列表
    }




    @RequestMapping("/sendMessageAll/{id}")
    public String sendMessageAll(@PathVariable("id") String id)
    {
        System.out.println("准备发送消息:");
        simpMessagingTemplate.convertAndSend("/topic/subscribeTest/"+id,"你好");
        return "发送成功";
    }


    @RequestMapping("/sendMessageOne")
    public String sendMessageOne()
    {
        System.out.println("准备发送消息");
        simpMessagingTemplate.convertAndSendToUser("admin_","/queue/test","Hello,world");
        return "发送成功";
    }


    @MessageMapping("/user/queue/MessageTest")
    public void MessageTest(Principal principal, Message msg) throws Exception {
        System.out.println("有人发消息来了,"+principal.getName()+","+msg.getMessage()+","+msg.getTo());
       // simpMessagingTemplate.convertAndSendToUser("admin_","/queue/test","Hello,world");
        simpMessagingTemplate.convertAndSendToUser(msg.getTo(),"/queue/test",msg.getMessage());
    }


    @MessageMapping("/topic/subscribeTest")
    public void sendMessageAll(Principal principal, Message msg)
    {
        System.out.println("准备发送消息");
        simpMessagingTemplate.convertAndSend("/topic/subscribeTest",msg.getMessage());
    }

}
